package org.redis.cluster.transport.netty.test;

import java.util.List;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

public class NettyClientTester_1 {

	public static void main(String[] args) throws Exception {
		Bootstrap bootstrap=new Bootstrap();
		EventLoopGroup workerGroup=new NioEventLoopGroup(1);
		bootstrap.group(workerGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
            	ch.pipeline().addLast("decoder", new TestDecoder_2());
            	ch.pipeline().addLast("encoder", new TestEncoder_2());
            	ch.pipeline().addLast("handler", new TestHandler());
            }
        });

        ChannelFuture future=bootstrap.connect("127.0.0.1", 6379).sync();
        Channel channel=future.channel();
        
        channel.writeAndFlush("*1\r\n$4\r\nPING\r\n".getBytes());
        System.in.read();
	}
}

class TestHandler extends SimpleChannelInboundHandler<Object>  {
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(msg);
	}
}

class TestDecoder_2 extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		while(in.isReadable()) {
			byte read=in.readByte();
			System.out.println((char) read);
			
			out.add(read);
		}
	}
}

class TestEncoder_2 extends MessageToByteEncoder<Object> {

	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
		out.writeBytes((byte[]) msg);
	}
	
}
